#include <QtGui>
#include "mainWindow.h"

MainWindow::MainWindow() { 

  russianCodec = QTextCodec::codecForName("UTF-8");
  QTextCodec::setCodecForTr(russianCodec);
  QTextCodec::setCodecForCStrings(russianCodec);

  opacity = 1.0;

  //Ставит размер и заголовок главного виджета
  this->resize(WMAIN, HMAIN);
  this->setMaximumSize(WMAIN, HMAIN);
  this->setMinimumSize(WMAIN, HMAIN);
  this->setWindowTitle(MAINTITLE);

  this->setWindowIcon(QIcon(QPixmap(":/resources/icon.ico")));

  //Создание действий
  createActions();
  //Создает пункты меню
  createMenus();
  //Создает статус бар
  createStatusBar();

  ttk = new TrayToolKit();

  dConcrete = NULL;
  dTypeUpside = NULL;
  dRegion = NULL;
  dMap = NULL;
  dAuthors = NULL;
  dClassConcrete = NULL;
  dReport = NULL;

  qApp->setStyleSheet(
		      "QTreeWidget::branch:closed:has-children:!has-siblings," 
		      "QTreeWidget::branch:closed:has-children:has-siblings {"
		         "border-image: none;" 
		         "image: url(':/resources/closeDecorated.png');"
		      "}"
		      
		      "QTreeWidget::branch:open:has-children:!has-siblings,"
		      "QTreeWidget::branch:open:has-children:has-siblings  {"
		         "border-image: none;"
          		 "image: url(':/resources/openDecorated.png');"
 		      "}"
		      );

  tam = new TermsAndMaterials(this);

  tam->setValueDoubleSpin(ttk->getVar(VAR_N), EDIT_N);
  tam->setValueIntSpin(ttk->environment(VAR_REGION), EDIT_REGION);
  tam->setValueDoubleSpin(ttk->getVar(VAR_P), EDIT_P);
  tam->setValueDoubleSpin(ttk->getVar(VAR_I), EDIT_I);
  tam->setValueDoubleSpin(ttk->getVar(VAR_F), EDIT_F);
  tam->setValueIntSpin(ttk->getVar(VAR_Q20), EDIT_Q20);
  tam->setValueDoubleSpin(ttk->getVar(VAR_ZMID), EDIT_ZMID);
  tam->setValueIntSpin(ttk->environment(VAR_TIMERAIN), EDIT_T);
  tam->setValueDoubleSpin(ttk->getVar(VAR_I), EDIT_IR);
  tam->setValueDoubleSpin(ttk->getVar(VAR_H), EDIT_HR);
  tam->setTextLabel(ttk->getNameClassConcrete(), EDIT_CLCONCRETE);

  tam->setAddStr("", EDIT_N);
  tam->setAddStr("", EDIT_REGION);
  tam->setAddStr(" лет", EDIT_P);
  tam->setAddStr("", EDIT_I);
  tam->setAddStr(" га", EDIT_F);
  tam->setAddStr(" л/с на га", EDIT_Q20);
  tam->setAddStr("", EDIT_ZMID);
  tam->setAddStr(" мин", EDIT_T);
  tam->setAddStr("", EDIT_IR);
  tam->setAddStr(" м", EDIT_HR);

//Вызов диалогов
  connect(tam, SIGNAL(callDConcrete()),   this, SLOT(createDConcrete()));
  connect(tam, SIGNAL(callDRegion()),     this, SLOT(createDRegion()));
  connect(tam, SIGNAL(callDMap()),        this, SLOT(createDMap()));
  connect(tam, SIGNAL(callDTypeUpside()), this, SLOT(createDTypeUpside()));
  connect(tam, SIGNAL(callDClConcrete()), this, SLOT(createDClassConcrete()));

//Вычисления при изменении переменных
  connect(tam, SIGNAL(callCalcWithNewN(double)),	   this, SLOT(calcWithNewN(double)));
  connect(tam, SIGNAL(callCalcWithNewRegion(int)),    	   this, SLOT(calcWithNewRegion(int)));
  connect(tam, SIGNAL(callCalcWithNewP(double)), 	   this, SLOT(calcWithNewP(double)));
  connect(tam, SIGNAL(callCalcWithNewI(double)), 	   this, SLOT(calcWithNewI(double)));
  connect(tam, SIGNAL(callCalcWithNewF(double)), 	   this, SLOT(calcWithNewF(double)));
  connect(tam, SIGNAL(callCalcWithNewQ20(int)), 	   this, SLOT(calcWithNewQ20(int)));
  connect(tam, SIGNAL(callCalcWithNewRunnel(double)), 	   this, SLOT(calcWithNewRunnel(double)));
  connect(tam, SIGNAL(callCalcWithNewTime(int)), 	   this, SLOT(calcWithNewTime(int)));
  connect(tam, SIGNAL(callCalcWithNewIr(double)), 	   this, SLOT(calcWithNewIr(double)));
  connect(tam, SIGNAL(callCalcWithNewHr(double)), 	   this, SLOT(calcWithNewHr(double)));
  connect(tam, SIGNAL(newMessage(QString)), 	   	   this, SLOT(showMessage(QString)));
  connect(tam, SIGNAL(callUpdateConcrete(int)),   	   this, SLOT(updateClassConcrete(int)));

  //Создает чертеж и его параметры
  chart = new ChartTray(this);
  chart->move(XSHIFT, UP+YSHIFT);
  chart->resize(WIDTH1, HEIGHT1);
  // chart->move(10, UP+5);
  // chart->resize(WCHART, HCHART);
  chart->update();

  connect(tam, SIGNAL(callCalcWithNewHr(double)), chart, SLOT(setHr(double)));

  //Смена типа
  connect(chart, SIGNAL(changeTrayType(int)), this, SLOT(setTrayType(int)));

  listTray  = new QWidget(this);
  listParts = new QWidget(this);

  chartParts = new ChartParts(ttk, listParts);
  chartParts->move(XSHIFT, YSHIFT);
  chartParts->resize(WTABSITEM, HTABSITEM);
  chartParts->setCursor(Qt::PointingHandCursor);
  // chartParts->resize(WIDTH1+SPACE+WIDTH2-XSHIFT*2-10, HEIGHT3-YSHIFT*2-30);
  chartParts->update();
    
  result = new Result(this);
  result->move(XSHIFT+WIDTH1+SPACE, UP+YSHIFT);
  result->resize(WIDTH2, HEIGHT1+SPACE+HEIGHT2);
  // result->move(chart->width()+10+5, UP+5);
  // result->resize(WRESULT, HRESULT);

  //Единицы измерения для выводимых в ChartTray переменных
  QString addStr("");

  addStr = " "; addStr += S_DIM_HTML;
  result->setAddStrArea(addStr);

  addStr = " "; addStr += X_DIM_HTML;
  result->setAddStrPerimeter(addStr);

  addStr = " "; addStr += R_DIM_HTML;
  result->setAddStrRadius(addStr);

  addStr = " "; addStr += C_DIM_HTML;
  result->setAddStrShezy(addStr);

  addStr = " "; addStr += EMPTY_DIM;
  result->setAddStrAQ(addStr);

  addStr = " "; addStr += Q_DIM_HTML;
  result->setAddStrRainCon(addStr);

  addStr = " "; addStr += Q_DIM_HTML;
  result->setAddStrQr(addStr);

  addStr = " "; addStr += Q_DIM_HTML;
  result->setAddStrQcr(addStr);

  addStr = " "; addStr += Q_DIM_HTML;
  result->setAddStrQrec(addStr);

  addStr = " "; addStr += H_DIM_HTML;
  result->setAddStrHrain(addStr);

  addStr = " "; addStr += H_DIM_HTML;
  result->setAddStrHcr(addStr);

  addStr = " "; addStr += H_DIM_HTML;
  result->setAddStrHrec(addStr);

  addStr = " "; addStr += EMPTY_DIM;
  result->setAddStrIcr(addStr);

  addStr = " "; addStr += V_DIM_HTML;
  result->setAddStrVs(addStr);
  addStr = " "; addStr += V_DIM_HTML;
  result->setAddStrVr(addStr);
  addStr = " "; addStr += V_DIM_HTML;
  result->setAddStrVd(addStr);

  toolLab = new QLabel(listTray);
  toolLab->move(XSHIFT, YSHIFT);
  toolLab->setText("<b>Параметры лотка по участкам</b>");

  toolItem = new ToolParts(listTray);
  toolItem->move(XSHIFT, YSHIFT+21);
  toolItem->resize(WTABSITEM, HTABSITEM-21);
  toolItem->setCursor(Qt::PointingHandCursor);
  // toolItem->resize(WIDTH1+SPACE+WIDTH2-XSHIFT*2-10, HEIGHT3-YSHIFT*2-30);
  
  connect(toolItem, SIGNAL(changedF(double)), 	    chartParts, SLOT(changeF(double)));
  connect(toolItem, SIGNAL(changedI(double)), 	    chartParts, SLOT(changeI(double)));
  connect(toolItem, SIGNAL(changedIr(double)), 	    chartParts, SLOT(changeIr(double)));
  connect(toolItem, SIGNAL(changedL(double)), 	    chartParts, SLOT(changeL(double)));
  connect(toolItem, SIGNAL(changedCurPart(int)),    chartParts, SLOT(setCurItem(int)));
  connect(toolItem, SIGNAL(changedCurPart(int)),    chart, 	SLOT(setNumPart(int)));
  connect(toolItem, SIGNAL(newMessage(QString)),    this, 	SLOT(showMessage(QString)));

  toolItem->setL(DEFLENGTH,           0);
  toolItem->setF(ttk->getVar(VAR_F),  0);
  toolItem->setI(ttk->getVar(VAR_I),  0);
  toolItem->setIr(ttk->getVar(VAR_I), 0);

  connect(toolItem, SIGNAL(changedF(double)), 	    this, SLOT(calcWithNewF(double)));
  connect(toolItem, SIGNAL(changedI(double)), 	    this, SLOT(calcWithNewI(double)));
  connect(toolItem, SIGNAL(changedIr(double)), 	    this, SLOT(calcWithNewIr(double)));

  connect(toolItem, SIGNAL(changedValue()), 	    this, SLOT(setChanged()));
  
  connect(chartParts, SIGNAL(changedCurPart(int)), toolItem, SLOT(changeCurPart(int)));
  connect(chartParts, SIGNAL(changedCurPart(int)), chart, SLOT(setNumPart(int)));

  grControl = new GroupControl(this);
  grControl->move(XSHIFT, UP+YSHIFT+HEIGHT1+SPACE);
  grControl->resize(WIDTH1, HEIGHT2);
  // grControl->move(10, chart->height()+UP+10);
  // grControl->resize(WGROUPBOX, HGROUPBOX);

  //b
  grControl->setWidth(ttk->getVar(VAR_B));
  connect(grControl, SIGNAL(callCalcWithNewB(double)), this, SLOT(calcWithNewB(double)));
  connect(grControl, SIGNAL(callCalcWithNewB(double)), chart, SLOT(setB(double)));

  //h
  grControl->setHeight(ttk->getVar(VAR_H));
  connect(grControl, SIGNAL(callCalcWithNewH(double)), this, SLOT(calcWithNewH(double)));
  connect(grControl, SIGNAL(callCalcWithNewH(double)), chart, SLOT(setH(double)));

  //hr
  grControl->setRHeight(ttk->getVar(VAR_HR));
  connect(grControl, SIGNAL(callCalcWithNewHR(double)), this, SLOT(calcWithNewHr(double)));
  connect(grControl, SIGNAL(callCalcWithNewHR(double)), chart, SLOT(setHr(double)));

  //Угол
  grControl->setGr(   to_gr(  atan(1/ttk->getVar(VAR_M))  )   );
  connect(grControl, SIGNAL(callCalcWithNewAngle(int)), this, SLOT(calcWithNewAngle(int)));
  connect(grControl, SIGNAL(callCalcWithNewAngle(int)), chart, SLOT(setAngle(int)));

  //Соединени со статус баром
  connect(grControl, SIGNAL(callUpdateStatus(QString)), this, SLOT(showMessage(QString)));

  report = new Report(ttk, toolItem, tam, grControl, this);
  report->hide();
  report->move(-50, -50);
  report->resize(1, 1);
  connect(report, SIGNAL(callReCalc()), this, SLOT(reCalc()));
  connect(report, SIGNAL(newMessage(QString)), this, SLOT(showMessage(QString)));

  connect(exportXmlPatternAction, SIGNAL(triggered()), this, SLOT(createReport()));
  // connect(exportXmlPatternAction, SIGNAL(triggered()), report, SLOT(saveXmlPattern()));

  connect(exportXmlFileAction, SIGNAL(triggered()), report, SLOT(genXmlReport()));
  connect(exportXmlFileAsAction, SIGNAL(triggered()), report, SLOT(saveAsXmlPattern()));
  connect(importXmlFileAction, SIGNAL(triggered()), this, SLOT(checkChanged()));
  connect(report, SIGNAL(resetChanged(bool)), this, SLOT(setChanged(bool)));

  tabs = new QTabWidget(this);
  tabs->move(XSHIFT, UP+YSHIFT+HEIGHT1+SPACE+HEIGHT2+SPACE);
  tabs->resize(WIDTH1+SPACE+WIDTH2, HEIGHT3);
  // tabs->move(10, chart->height()+grControl->height()+UP+20);
  // tabs->resize(WTABS, HTABS);
  tabs->insertTab(0, tam, "Условия и материалы");
  tabs->insertTab(1, listTray, "Параметры участков");
  tabs->insertTab(2, listParts, "Изображение участков");
  // tabs->insertTab(3, report, "Отчет");

  connect(tabs, SIGNAL(currentChanged(int)), this, SLOT(showColorCharts(int)));

//Инициация вычислений при запуске
  reCalc();
  showMessage("");
  setChanged(false);
  toolItem->setFocusF();

} //MainWindow::MainWindow()

void MainWindow::createReport() {

  createDReport(report->saveReport());

} //void MainWindow::createReport()

void MainWindow::showColorCharts(int numTab) {

  if (numTab == 0)
    toolItem->setFocusF();
  else if (numTab == 1)
    showMessage("");
  else if (numTab == 2)
    showMessage("<b>Легенда:</b> Условие для уклона: <font color=darkblue>Выполняется</font> / <font color=darkred>не выполняется</font>. Высота заполнения: <font color=darkblue>H<sub>r</sub></font> / <font color=darkred>H<sub>cr</sub></font> / <font color=darkgreen>H<sub>rain</sub></font>");
  else if (numTab == 3)
    showMessage("");

} //void MainWindow::showColorCharts(int numTab)

void MainWindow::checkChanged() {

  if (isChanges()) {
  
    QMessageBox msgBox;
    msgBox.setWindowTitle("Закрыть расчеты - Mantissa");
    msgBox.setText("Данные были изменены.");
    msgBox.setInformativeText("Сохранить изменения или отклонить их?");
    QPushButton *saveButton = msgBox.addButton("Сохранить", QMessageBox::ActionRole);
    QPushButton *discardButton = msgBox.addButton("Отклонить", QMessageBox::ActionRole);
    msgBox.addButton("Отмена", QMessageBox::ActionRole);

    msgBox.exec();

    if (msgBox.clickedButton() == saveButton) {

      report->genXmlReport();
      report->loadXmlReport();

    } //if (msgBox.clickedButton() == saveButton)

    else if (msgBox.clickedButton() == discardButton) {

      report->loadXmlReport();

    } //else if (msgBox.clickedButton() == discardButton)

  } //if (isChanges())

  else {
 
    report->loadXmlReport();

  } //else: if (isChanges())

} //void MainWindow::checkChanged()

void MainWindow::reCalc() {

  calcConQ(grControl->getWidth(), grControl->getHeight(), grControl->getGr(), toolItem->i(0));
  calcConRainq(getQ20(), toolItem->f(0), getPeriod());
  calcQr(grControl->getWidth(), grControl->getRHeight(), grControl->getGr(), toolItem->ir(0));

} //void MainWindow::reCalc()

void MainWindow::setChanged(bool newVal) {

  QString title("");
  title += MAINTITLE;

  isChanged = newVal; 

  if (isChanged) {

    title += " [Изменен]";

  } //if (isChanged)

  this->setWindowTitle(title);  
  
} //void MainWindow::setChanged(bool newVal)

//СОЗДАНИЕ ДИАЛОГОВ
void MainWindow::createDConcrete() {

  if (!dConcrete) {

    dConcrete = new ConcreteDialog();
    dConcrete->setWindowIcon(QIcon(QPixmap(":/resources/icon.ico")));
    // dConcrete->setWindowFlags(Qt::Tool);
    connect(dConcrete, SIGNAL(selectClass(int)), this, SLOT(updateConcrete(int)));

  } //if (!dConcrete)

  dConcrete->move(this->x()+XSHIFT+rint(WIDTH1/2), this->y()+UP+HEIGHT1+HEIGHT2);
  dConcrete->setWindowModality(Qt::WindowModal);
  dConcrete->show();
  dConcrete->activateWindow();

} //void MainWindow::createDConcrete()

void MainWindow::createDTypeUpside() {

  if (!dTypeUpside) {

    dTypeUpside = new TypeUpsideDialog();
    dTypeUpside->setWindowIcon(QIcon(QPixmap(":/resources/icon.ico")));
    // dTypeUpside->setWindowFlags(Qt::Tool);
    connect(dTypeUpside, SIGNAL(selectClass(int)), this, SLOT(updateTypeUpside(int)));

  } //if (!dTypeUpside)

  dTypeUpside->move(this->x()+XSHIFT+180, this->y()+UP+HEIGHT1+HEIGHT2+10);
  dTypeUpside->setWindowModality(Qt::WindowModal);
  dTypeUpside->show();
  dTypeUpside->activateWindow();
  
} //void MainWindow::createDTypeUpside()

void MainWindow::createDRegion() {

  if (!dRegion) {

    dRegion = new RegionDialog();
    dRegion->setWindowIcon(QIcon(QPixmap(":/resources/icon.ico")));
    // dRegion->setWindowFlags(Qt::Tool);
    connect(dRegion, SIGNAL(selectClass(int)), this, SLOT(updateRegion(int)));

  } //if (!dRegion)

  dRegion->move(this->x()+XSHIFT+5, this->y()+UP+HEIGHT1-25);
  dRegion->selectRow(ttk->environment(VAR_REGION));
  dRegion->setWindowModality(Qt::WindowModal);
  dRegion->show();
  dRegion->activateWindow();
  
} //void MainWindow::createDRegion()

void MainWindow::createDMap() {

  if (!dMap) {

    dMap = new MapQ20Dialog();
    dMap->setWindowIcon(QIcon(QPixmap(":/resources/icon.ico")));
    // dMap->setWindowFlags(Qt::Tool);

  } //if (!dMap)

  dMap->move(100, 100);
  dMap->show();
  dMap->activateWindow();

} //void MainWindow::createDMap()

void MainWindow::createDReport(const QString & text) {

  if (!dReport) {

    dReport = new ReportDialog();
    dReport->setWindowIcon(QIcon(QPixmap(":/resources/icon.ico")));
    // dReport->setWindowFlags(Qt::Tool);

  } //if (!dReport)

  dReport->setHtml(text);

  dReport->move(this->x(), this->y());
  dReport->resize(this->width(), this->height());
  dReport->show();
  dReport->activateWindow();

} //void MainWindow::createDReport(const QString & text)

void MainWindow::createDAuthors() {

  if (!dAuthors) {

    dAuthors = new AboutAuthorsDialog();
    dAuthors->setWindowIcon(QIcon(QPixmap(":/resources/icon.ico")));
    // dAuthors->setWindowFlags(Qt::Tool);

  } //if (!dAuthors)

  dAuthors->move(100, 100);
  dAuthors->show();
  dAuthors->activateWindow();

} //void MainWindow::createDAuthors()

void MainWindow::createDClassConcrete() {

  if (!dClassConcrete) {

    dClassConcrete = new ClassConcreteDialog();
    dClassConcrete->setWindowIcon(QIcon(QPixmap(":/resources/icon.ico")));
    // dClassConcrete->setWindowFlags(Qt::Tool);
    connect(dClassConcrete, SIGNAL(selectClass(int)), this, SLOT(updateClassConcrete(int)));

  } //if (!dClassConcrete)

  dClassConcrete->move(this->x()+XSHIFT+145, this->y()+UP+HEIGHT1+HEIGHT2);
  dClassConcrete->selectRow(ttk->environment(VAR_CLCONCRETE));
  dClassConcrete->setWindowModality(Qt::WindowModal);
  dClassConcrete->show();
  dClassConcrete->activateWindow();
  
} //void MainWindow::createDClassConcrete()

// void MainWindow::createDLicense() {
// 
//   if (!dLicense) {
// 
//     dLicense = new LicenseDialog();
//     dLicense->setWindowIcon(QIcon(QPixmap(":/resources/icon.ico")));
//     // dLicense->setWindowFlags(Qt::Tool);
//     // connect(dLicense, SIGNAL(selectClass(int)), this, SLOT(updateClassConcrete(int)));
// 
//   } //if (!dLicense)
// 
//   dLicense->move(this->x()+XSHIFT+145, this->y()+UP+HEIGHT1+HEIGHT2);
//   // dLicense->selectRow(ttk->environment(VAR_CLCONCRETE));
//   dLicense->setWindowModality(Qt::WindowModal);
//   dLicense->show();
//   dLicense->activateWindow();
// 
// } //void MainWindow::createDLicense()

//ОБРАБОТКА ДИАЛОГОВ
void MainWindow::updateConcrete(int num) {

  ttk->setEnvironment(num, VAR_CONCRETE);
  tam->setValueDoubleSpin(ttk->getVar(VAR_N), EDIT_N);

} //void MainWindow::updateConcrete(int num)

void MainWindow::updateTypeUpside(int num) {

  ttk->setEnvironment(num, VAR_TYPEUPSIDE);
  tam->setValueDoubleSpin(ttk->getVar(VAR_ZMID), EDIT_ZMID);

} //void MainWindow::updateTypeUpside(int num)

void MainWindow::updateRegion(int reg) {

  int num = 0;

  switch (reg) {

    case 0:          num =  0; break;
    case 1:          num =  1; break;
    case 2:          num =  2; break;
    case 3:          num =  3; break;
    case 4:          num =  4; break;
    case 5:          num =  5; break;
    case 6:          num =  6; break;
    case 7:          num =  7; break;
    case 8:          num =  8; break;
    case 9:          num =  8; break;
    case 10:	     num =  9; break;
    case 11:	     num =  9; break;
    case 12:	     num =  9; break;
    case 13:         num = 10; break;
    case 14:         num = 10; break;
    case 15:         num = 11; break;
    case 16:         num = 12; break;
    case 17:         num = 13; break;
    case 18:         num = 14; break;
    case 19:         num = 15; break;
    case 20:         num = 16; break;
    case 21:         num = 17; break;
    case 22:  	     num = 18; break;
    case 23:         num = 19; break;
    case 24:         num = 19; break;
    case 25:	     num = 20; break;
    case 26:	     num = 20; break;
    case 27: 	     num = 21; break;
    case 28: 	     num = 22; break;
    case 29: 	     num = 23; break;
    case 30: 	     num = 24; break;
    case 31:         num = 25; break;
    case 32:         num = 25; break;
    case 33: 	     num = 26; break;
    case 34: 	     num = 27; break;
    case 35:         num = 28; break;
    case 36:         num = 28; break;
    case 37: 	     num = 29; break;
    case 38:         num = 30; break;
    case 39:         num = 30; break;
    case 40:         num = 31; break;
    case 41:         num = 31; break;
    case 42:         num = 32; break;
    case 43:         num = 32; break;
    case 44:         num = 33; break;
    case 45:         num = 33; break;
    case 46: 	     num = 34; break;
    case 47: 	     num = 35; break;

  } //switch (reg)

  tam->setValueIntSpin(reg, EDIT_REGION);
  ttk->setEnvironment(num, VAR_REGION);

} //void MainWindow::updateRegion(int num)

void MainWindow::updateClassConcrete(int num) {

  ttk->setEnvironment(num, VAR_CLCONCRETE);
  tam->setTextLabel(ttk->getNameClassConcrete(), EDIT_CLCONCRETE);
  result->setVd(ttk->getVar(VAR_VD));
  chart->setVd(ttk->getVar(VAR_VD));

} //void MainWindow::updateClassConcrete(int num)

//Класс бетона
double MainWindow::getN() {

  return tam->valueDoubleSpin(EDIT_N);

} //double MainWindow::getN()

void MainWindow::setN(double newVal) {

  tam->setValueDoubleSpin(newVal, EDIT_N);

} //void MainWindow::setN(double newVal)

//Регион
int MainWindow::getRegion() {

  return tam->valueIntSpin(EDIT_REGION);

} //int MainWindow::getRegion()

void MainWindow::setRegion(int newVal) {

  tam->setValueIntSpin(newVal, EDIT_REGION);

} //void MainWindow::setRegion(int newVal)

//Период
double MainWindow::getPeriod() {

  return tam->valueDoubleSpin(EDIT_P);

} //double MainWindow::getPeriod()

void MainWindow::setPeriod(double newVal) {

  tam->setValueDoubleSpin(int(newVal), EDIT_P);

} //void MainWindow::setPeriod(double newVal)

//Гидравлический уклон
double MainWindow::getHydraInc() {

  return toolItem->curI();

} //double MainWindow::getHydraInc()

void MainWindow::setHydraInc(double newVal) {

  toolItem->setCurI(newVal);

} //void MainWindow::setHydraInc(double newVal)

//Площадь стока
double MainWindow::getF() {

  return toolItem->curF();

} //double MainWindow::getF()

void MainWindow::setF(double newVal) {

  toolItem->setCurF(newVal);

} //void MainWindow::setF(double newVal)

//Интенсивность дождя
int MainWindow::getQ20() {

  return tam->valueIntSpin(EDIT_Q20);

} //int MainWindow::getQ20()

void MainWindow::setQ20(int newVal) {
  
  tam->setValueIntSpin(newVal, EDIT_Q20);

} //void MainWindow::setQ20(int newVal)

double MainWindow::getCofRunnel() {

  return tam->valueDoubleSpin(EDIT_ZMID);

} //double MainWindow::getCofRunnel()

void MainWindow::setCofRunnel(double newVal) {
  
  tam->setValueDoubleSpin(newVal, EDIT_ZMID);

} //void MainWindow::setCofRunnel(double newVal)

int MainWindow::getTimeRain() {

  return tam->valueIntSpin(EDIT_T);

} //int MainWindow::getTimeRain()

void MainWindow::setTimeRain(int newVal) {
  tam->setValueIntSpin(newVal, EDIT_T);

} //void MainWindow::setTimeRain()

double MainWindow::getIr() {

  return toolItem->curIr();

} //double MainWindow::getIr()

void MainWindow::setIr(double newVal) {
  
  toolItem->setCurIr(newVal);

} //void MainWindow::setIr(double newVal)

double MainWindow::getHr() {

  return tam->valueDoubleSpin(EDIT_HR);

} //double MainWindow::getHr()

void MainWindow::setHr(double newVal) {
  
  tam->setValueDoubleSpin(newVal, EDIT_HR);

} //void MainWindow::setHr(double newVal)

void MainWindow::calcConQ(double newB, double newH, int angle, double newI) {

  ttk->setVar(newB, VAR_B);
  ttk->setVar(newH, VAR_H);
  ttk->setVar( 1/tan(to_rad(angle)), VAR_M );
  ttk->setVar(newI, VAR_I);

  result->setArea(ttk->areaLiveProfile());
  result->setIcr(ttk->crHydraulicInclination());
  result->setPerimeter(ttk->moistenedPerimeter());
  result->setRadius(ttk->hydraulicRadius());
  result->setShezy(ttk->shezy());
  result->setAQ(ttk->calcAQ());

  result->setqRainCon(ttk->rainWaterConsumption());
  result->setQr(ttk->calcWaterConsumption());
  result->setQcr(ttk->crWaterConsumption());
  result->setQrec(ttk->recWaterConsumption());

  result->setHrain(ttk->getVar(VAR_HRAIN));
  result->setHcr(ttk->crHeightTrapTray());
  result->setHrec(ttk->recHeightTrapTray());

  result->setVd(ttk->getVar(VAR_VD));
  result->setVs(ttk->getVar(VAR_VS));
  result->setVr(ttk->getVar(VAR_VR));

  chart->setHrain(ttk->getVar(VAR_HRAIN));
  chart->setVd(ttk->getVar(VAR_VD));
  chart->setVs(ttk->getVar(VAR_VS));
  chart->setVr(ttk->getVar(VAR_VR));

  chart->setHcr(ttk->crHeightTrapTray());
  chart->setQcr(ttk->crWaterConsumption());
  chart->setQ(ttk->waterConsumption());

  chartParts->update();

} //void MainWindow::calcConQ(double newB, double newH, int angle, double newI)

void MainWindow::calcConRainq(int newQ20, double newF, double newP) {

  ttk->setVar(double(newQ20), VAR_Q20);
  ttk->setVar(newF, VAR_F);
  ttk->setVar(newP, VAR_P);

  result->setArea(ttk->areaLiveProfile());
  result->setIcr(ttk->crHydraulicInclination());
  result->setPerimeter(ttk->moistenedPerimeter());
  result->setRadius(ttk->hydraulicRadius());
  result->setShezy(ttk->shezy());
  result->setAQ(ttk->calcAQ());

  result->setqRainCon(ttk->rainWaterConsumption());
  result->setQr(ttk->calcWaterConsumption());
  result->setQcr(ttk->crWaterConsumption());
  result->setQrec(ttk->recWaterConsumption());

  result->setHrain(ttk->getVar(VAR_HRAIN));
  result->setHcr(ttk->crHeightTrapTray());
  result->setHrec(ttk->recHeightTrapTray());

  result->setVd(ttk->getVar(VAR_VD));
  result->setVs(ttk->getVar(VAR_VS));
  result->setVr(ttk->getVar(VAR_VR));

  chart->setHrain(ttk->getVar(VAR_HRAIN));
  chart->setVd(ttk->getVar(VAR_VD));
  chart->setQrain(ttk->rainWaterConsumption());
  chart->setQcr(ttk->crWaterConsumption());

  chartParts->update();

} //void MainWindow::calcConRainq(double newQ20, double newF, double newP)

void MainWindow::calcQr(double newB, double newHr, int angle, double newIr) {

  ttk->setVar(newB, VAR_B);
  ttk->setVar(newHr, VAR_HR);
  ttk->setVar(1/tan(to_rad(angle)), VAR_M);
  ttk->setVar(newIr, VAR_IR);

  result->setArea(ttk->areaLiveProfile());
  result->setIcr(ttk->crHydraulicInclination());
  result->setPerimeter(ttk->moistenedPerimeter());
  result->setRadius(ttk->hydraulicRadius());
  result->setShezy(ttk->shezy());
  result->setAQ(ttk->calcAQ());

  result->setqRainCon(ttk->rainWaterConsumption());
  result->setQr(ttk->calcWaterConsumption());
  result->setQcr(ttk->crWaterConsumption());
  result->setQrec(ttk->recWaterConsumption());

  result->setHrain(ttk->getVar(VAR_HRAIN));
  result->setHcr(ttk->crHeightTrapTray());
  result->setHrec(ttk->recHeightTrapTray());

  result->setVd(ttk->getVar(VAR_VD));
  result->setVs(ttk->getVar(VAR_VS));
  result->setVr(ttk->getVar(VAR_VR));

  chart->setHrain(ttk->getVar(VAR_HRAIN));
  chart->setVd(ttk->getVar(VAR_VD));
  chart->setVs(ttk->getVar(VAR_VS));
  chart->setVr(ttk->getVar(VAR_VR));
  chart->setQr(ttk->calcWaterConsumption());

  chartParts->update();

} //void MainWindow::calcConQ(double newB, double newH, int angle, double newI)

void MainWindow::showMessage(const QString & message) {

  QString mdfMes("");

  mdfMes += "  ";
  mdfMes += message;

  quickMessage->setText(mdfMes);

} //void MainWindow::showMessage(const QString & message)

void MainWindow::createStatusBar() {

  statusBar = new QStatusBar(this);
  statusBar->move(0, this->height()-DOWN);
  statusBar->resize(this->width(), DOWN);

  quickMessage = new QLabel("");
  quickMessage->setMinimumSize(statusBar->width(), statusBar->height());
  quickMessage->setIndent(3);

  statusBar->addWidget(quickMessage);

} //void MainWindow::createStatusBar()

void MainWindow::createMenus() {

  fileMenu = menuBar()->addMenu(tr("Файл"));
  fileMenu->addAction(importXmlFileAction);
  fileMenu->addSeparator();
  fileMenu->addAction(exportXmlFileAction);
  fileMenu->addAction(exportXmlFileAsAction);
  fileMenu->addSeparator();
  fileMenu->addAction(exportXmlPatternAction);
  fileMenu->addSeparator();
  fileMenu->addAction(exitAction);

  fileMenu = menuBar()->addMenu(tr("Помощь"));
  fileMenu->addAction(helpAction);
  fileMenu->addAction(markAction);
  fileMenu->addAction(aboutAuthorsAction);
  fileMenu->addAction(aboutQtAction);
  fileMenu->addAction(licenseAction);

} //void MainWindow::createMenus()

void MainWindow::createActions() {

  importXmlFileAction = new QAction(tr("Открыть"), this);
  importXmlFileAction->setShortcut(tr("Ctrl+o"));

  exportXmlFileAction = new QAction(tr("Сохранить"), this);
  exportXmlFileAction->setShortcut(tr("Ctrl+s"));

  exportXmlFileAsAction = new QAction(tr("Сохранить как"), this);
  exportXmlFileAsAction->setShortcut(tr("Ctrl+Shift+s"));

  exportXmlPatternAction = new QAction(tr("Сгенерировать отчет"), this);
  exportXmlPatternAction->setShortcut(tr("Ctrl+r"));

  exitAction = new QAction(tr("Выход"), this);
  exitAction->setShortcut(tr("Alt+F4"));

  helpAction = new QAction(tr("Обозначение"), this);
  // connect(aboutAuthorsAction, SIGNAL(triggered()), this, SLOT(createDAuthors()));

  markAction = new QAction(tr("Справка"), this);
  // connect(aboutAuthorsAction, SIGNAL(triggered()), this, SLOT(createDAuthors()));

  aboutAuthorsAction = new QAction(tr("О Mantiss"), this);
  connect(aboutAuthorsAction, SIGNAL(triggered()), this, SLOT(createDAuthors()));

  aboutQtAction = new QAction(tr("О Qt"), this);
//   aboutQtAction->setStatusTip(tr("Показать информацию о Qt"));
  connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));

  licenseAction = new QAction(tr("Лицензия"), this);
//   aboutQtAction->setStatusTip(tr("Показать информацию о Qt"));
//   connect(licenseAction, SIGNAL(triggered()), qApp, SLOT(createDLicense()));

} //void MainWindow::createActions()

void MainWindow::setTrayType(int newTrayType) {

  ttk->setType(newTrayType);
  calcConQ(grControl->getWidth(), grControl->getHeight(), grControl->getGr(), getHydraInc());

  if (newTrayType == RECTANGLE) {

    grControl->setGrEnabled(false);
    showMessage("<b>Тип лотка:</b> условно прямоугольный");

  } //if (newTrayType == RECTANGLE)

  else if (newTrayType == ASYMTTRAPEZE) {

    grControl->setGrEnabled(true);
    showMessage("<b>Тип лотка:</b> асимметричный трапецеидальный");

  } //else if (newTrayType == ASYMTTRAPEZE)

  else if (newTrayType == SYMTTRAPEZE) {

    grControl->setGrEnabled(true);
    showMessage("<b>Тип лотка:</b> симметричный трапецеидальный");

  } //else if (newTrayType == SYMTTRAPEZE)

} //void MainWindow::setTrayType(int newTrayType)

void MainWindow::calcWithNewN(double newN) { 

  setChanged(true);
  ttk->setVar(newN, VAR_N); 
  calcConQ(grControl->getWidth(), grControl->getHeight(), grControl->getGr(), getHydraInc()); 

} //void MainWindow::calcWithNewN(double newN)

void MainWindow::calcWithNewRegion(int newRegion) { 

  setChanged(true);
  ttk->setEnvironment(newRegion, VAR_REGION); 
  calcConRainq(getQ20(), getF(), getPeriod()); 

} //void MainWindow::calcWithNewRegion(int newRegion)

void MainWindow::calcWithNewRunnel(double newRunnel) { 

  ttk->setVar(newRunnel, VAR_ZMID); 
  calcConRainq(getQ20(), getF(), getPeriod()); 

} //void MainWindow::calcWithNewRunnel(double newRunnel)

void MainWindow::calcWithNewB(double newB) { 

  setChanged(true);
  calcConQ(newB, grControl->getHeight(), grControl->getGr(), getHydraInc()); 

} //void MainWindow::calcWithNewB(double newB)

void MainWindow::calcWithNewH(double newH) { 

  setChanged(true);
  calcConQ(grControl->getWidth(), newH, grControl->getGr(), getHydraInc()); 

} //void MainWindow::calcWithNewH(double newH)

void MainWindow::calcWithNewHr(double newHr) { 

  setChanged(true);
  calcQr(grControl->getWidth(), newHr, grControl->getGr(), getIr()); 

} //void MainWindow::calcWithNewIr(double newHr)

void MainWindow::calcWithNewAngle(int newAngle) { 

  setChanged(true);
  calcConQ(grControl->getWidth(), grControl->getHeight(), newAngle, getHydraInc()); 

} //void MainWindow::calcWithNewAngle(int newAngle)

void MainWindow::calcWithNewI(double newI) { 

  calcConQ(grControl->getWidth(), grControl->getHeight(), grControl->getGr(), newI); 

} //void MainWindow::calcWithNewI(double newI)

void MainWindow::calcWithNewQ20(int newQ20) { 

  setChanged(true);
  calcConRainq(newQ20, getF(), getPeriod()); 

} //void MainWindow::calcWithNewQ20(int newQ20)

void MainWindow::calcWithNewF(double newF) { 

  calcConRainq(getQ20(), newF, getPeriod()); 

} //void MainWindow::calcWithNewF(double newF)

void MainWindow::calcWithNewP(double newP) { 

  setChanged(true);
  calcConRainq(getQ20(), getF(), newP); 

} //void MainWindow::calcWithNewP(double newP)

void MainWindow::calcWithNewTime(int newTime) { 

  setChanged(true);
  ttk->setEnvironment(newTime, VAR_TIMERAIN); calcConRainq(getQ20(), getF(), getPeriod()); 

} //void MainWindow::calcWithNewTime(int newTime)

void MainWindow::calcWithNewIr(double newIr) { 

  calcQr(grControl->getWidth(), grControl->getRHeight(), grControl->getGr(), newIr); 

} //void MainWindow::calcWithNewIr(double newIr)

void MainWindow::closeDialogs() {

  //Диалог для смены облицовки
  if (dConcrete) {
    dConcrete->hide();
    delete dConcrete;
  } //if (dConcrete)
  //Диалог для смены типа поверхности
  if (dTypeUpside) {
    dTypeUpside->hide();
    delete dTypeUpside;
  } //if (dTypeUpside)
  //Диалог для смены региона
  if (dRegion) {
    dRegion->hide();
    delete dRegion;
  } //if (dRegion)
  //Карта
  if (dMap) {
    dMap->hide();
    delete dMap;
  } //if (dMap)
  //Про авторов
  if (dAuthors) {
    dAuthors->hide();
    delete dAuthors;
  } //if (dAuthors)
  //Класс бетона
  if (dClassConcrete) {
    dClassConcrete->hide();
    delete dClassConcrete;
  } //if (dClassConcrete)

} //void MainWindow::closeDialogs()

void MainWindow::closeEvent(QCloseEvent * event) {

  if (isChanges()) {

    QMessageBox msgBox;
    msgBox.setWindowTitle("Закрыть приложение - Mantissa");
    msgBox.setText("Данные были изменены.");
    msgBox.setInformativeText("Сохранить изменения или отклонить их?");
    QPushButton *saveButton = msgBox.addButton("Сохранить", QMessageBox::ActionRole);
    QPushButton *discardButton = msgBox.addButton("Отклонить", QMessageBox::ActionRole);
    QPushButton *cancelButton = msgBox.addButton("Отмена", QMessageBox::ActionRole);

    msgBox.exec();

    if (msgBox.clickedButton() == saveButton) {

      report->genXmlReport();
      event->accept();

      //Закрытие диалогов
      closeDialogs();

    } //if (msgBox.clickedButton() == saveButton)

    else if (msgBox.clickedButton() == discardButton) {

      event->accept();

      //Закрытие диалогов
      closeDialogs();

    } //else if (msgBox.clickedButton() == discardButton)

    else if (msgBox.clickedButton() == cancelButton) {

      event->ignore();

    } //else if (msgBox.clickedButton() == cancelButton)

  } //if (isChanges())

  else {

    //Закрытие диалогов
    closeDialogs();

  } //else: if (isChanges())

} //void MainWindow::closeEvent(QCloseEvent * event)
 
void MainWindow::wheelEvent(QWheelEvent * event) {

  //Регулирование прозрачности
  if ((event->delta() > 0) && (event->modifiers() == Qt::AltModifier)) {

    if (opacity <= 1.0) {
      opacity += 0.1;
    } //if (opacity >= 0)

  } //if (event->delta() > 0)

  else if ((event->delta() < 0) && (event->modifiers() == Qt::AltModifier)) {

    if (opacity >= 0) {
      opacity -= 0.1;
    } //if (opacity >= 0)

  } //if (event->delta() > 0)

  this->setWindowOpacity(opacity);

} //void MainWindow::wheelEvent(QWheelEvent * event)
